package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.*;
import com.heima.article.service.ApArticleService;
import com.heima.common.constants.article.ArticleConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.behavior.BehaviorFeign;
import com.heima.feigns.user.UserFeign;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.behavior.dtos.ApArticleRelationDto;
import com.heima.model.behavior.pojos.ApCollection;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUserFollow;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Resource
    private AuthorMapper authorMapper;

    @Resource
    private ApArticleConfigMapper apArticleConfigMapper;

    @Resource
    private ApArticleContentMapper apArticleContentMapper;

    @Resource
    ApArticleMapper apArticleMapper;

    @Value("${file.oss.web-site}")
    private String webSite;

    @Resource
    private UserFeign userFeign;

    @Resource
    private BehaviorFeign behaviorFeign;

    @Resource
    private ApCollectionMapper apCollectionMapper;


    /**
     * 发布文章
     * @param articleDto
     * @return
     */
    @Override
    public ResponseResult saveArticle(ArticleDto articleDto) {
//        1. 检查参数
        if (articleDto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApArticle article = new ApArticle();
        BeanUtils.copyProperties(articleDto,article);
//        2. 根据作者名称查询作者信息
        ApAuthor author = authorMapper.selectOne
                (Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getName, article.getAuthorName()));
        if (author == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章关联的作者信息不存在");
        }
//        articleDto.setAuthorId(Long.valueOf(author.getId()));
        article.setAuthorName(author.getName());
//        3.判断文章id是否存在
        if (article.getId() == null) {
//        3.1 不存在,添加文章
//            评论
            article.setComment(0);
//            点赞
            article.setLikes(0);
//            收藏
            article.setCollection(0);
//            查看
            article.setViews(0);
//            保存
            save(article);
        } else {
//        3.2 存在
//        根据文章id查询 没有抛出异常 修改文章
            ApArticle apArticle = getById(articleDto.getId());
            if (apArticle == null) {
                log.info("文章信息为空 =>{}",articleDto.getId());
                CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"对应的文章信息不存在");
            }
        }
//        根据文章id删除配置信息
        apArticleConfigMapper.delete(Wrappers.<ApArticleConfig>lambdaQuery()
        .eq(ApArticleConfig::getArticleId,article.getId()));
//        根据文章id删除内容信息
        apArticleContentMapper.delete(Wrappers.<ApArticleContent>lambdaQuery()
        .eq(ApArticleContent::getArticleId,article.getId()));
//        修改文章内容
        updateById(article);
//        4. 添加文章内容信息
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(article.getId());
        apArticleContent.setContent(articleDto.getContent());
        apArticleContentMapper.insert(apArticleContent);
//        5. 添加文章配置信息
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(article.getId());
        apArticleConfig.setIsComment(true);
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsDelete(false);
        apArticleConfig.setIsDown(false);
        apArticleConfigMapper.insert(apArticleConfig);
//        6. 封装返回结果 携带文章id
        return ResponseResult.okResult(article.getId());
    }


    /**
     * 根据参数加载文章列表
     * @param loadtype 1为加载更多  2为加载最新
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDto dto) {
//        1. 校验参数
        if (dto.getSize() == null || dto.getSize() < 1 || dto.getSize() > 50) {
            dto.setSize(10);
        }
        if (dto.getMaxBehotTime() == null) {
            dto.setMaxBehotTime(new Date());
        }
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
        if (StringUtils.isBlank(dto.getTag())) {
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
//        2. 调用mapper方法查询列表
        List<ApArticle> apArticles = apArticleMapper.loadArticleList(dto, loadtype);
//        3. 封装返回结果
        ResponseResult result = ResponseResult.okResult(apArticles);
//        4. 加上图片访问路径
        result.setHost(webSite);
        return result;
    }


    /**
     * 加载文章详情
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArtilceInfo(ArticleInfoDto dto) {
//        1. 校验参数
        if (ObjectUtils.isEmpty(dto) || ObjectUtils.isEmpty(dto.getArticleId())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"无效参数或者文章id为空");
        }
//        2. 查询当前的文章id
        Long articleId = dto.getArticleId();
//        3. 查询文章配置信息
        ApArticleConfig articleConfig = apArticleConfigMapper.selectOne(Wrappers.<ApArticleConfig>lambdaQuery()
                .eq(ApArticleConfig::getArticleId, articleId));
//        进行判断
        if (ObjectUtils.isEmpty(articleConfig) || articleConfig.getIsDown() ||
        articleConfig.getIsDelete()) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章被下架或已被删除");
        }
//        4. 查询文章内容
        ApArticleContent articleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery()
                .eq(ApArticleContent::getArticleId, articleId));
        if (ObjectUtils.isEmpty(articleContent)) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章不存在");
        }
//        5. 封装结果返回
        Map<String, Object> map = new HashMap<>();
        map.put("config",articleConfig);
        map.put("content",articleContent);
        return ResponseResult.okResult(map);
    }


    /**
     * 加载文章的初始化详情 比如关注 喜欢 不喜欢
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {
//        1. 校验参数
        if (dto == null || dto.getArticleId() == null || dto.getAuthorId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        boolean iscollection = false , isfollow = false;
//        是否关注
        ApAuthor apAuthor = authorMapper.selectById(dto.getAuthorId());
        if (apAuthor != null) {
            ApUserFollow apUserFollow = userFeign.findByUserIdAndFollowId(AppThreadLocalUtils.getUser().getId(), apAuthor.getUserId());
            if (apUserFollow != null) {
                isfollow = true;
            }
        }
//        是否点赞 不喜欢
        ApArticleRelationDto relationDto = new ApArticleRelationDto();
        relationDto.setArticleId(dto.getArticleId());
        relationDto.setEntryId(AppThreadLocalUtils.getUser().getId());
        relationDto.setType((short)1);
        Map map = behaviorFeign.findApArticleRelation(relationDto);
//        收藏
        ApCollection apCollection = apCollectionMapper.selectOne(Wrappers.<ApCollection>lambdaQuery()
                .eq(ApCollection::getArticleId, dto.getArticleId())
                .eq(ApCollection::getEntryId, map.get("entryId")));
        if (apCollection != null) {
            iscollection = true;
        }
//        返回结果
        Map result = new HashMap();
        result.put("isfollow" , isfollow);
        result.put("iscollection" , iscollection);
        result.putAll(map);
        return ResponseResult.okResult(result);
    }

}